import { urlPrefix } from '@/utils/http';
import { request } from 'alita';
export const ACCESSTOKEN = 'ACCESSTOKEN';
const USE_INFO = 'USER_INFO';
const TTL = '_ttl';

import { xinghua,pingfang,chongqingguoce,hubeismartworker,daliangeosmarthub, baogangecg } from '@/constants';
import { UseAuthModel } from '@/models/useAuthModel';

export function setWithExpiry(key: string, value: string, ttl: number) {
  const now = new Date();

  // `item` is an object which contains the original value
  // as well as the time when it's supposed to expire


  const item = {
    value: value,
    expiry: now.getTime() + ttl,
  };

  localStorage.setItem(key + TTL, JSON.stringify(item));
  localStorage.setItem(key, value);
}

export function getWithExpiry(key: string): any {
  const ttlKey = `${key}${TTL}`;
  const itemStr = localStorage.getItem(ttlKey);
  // if the item doesn't exist, return null
  if (!itemStr) {
    return null;
  }
  const item = JSON.parse(itemStr);
  const now = new Date();
  // compare the expiry time of the item with the current time
  if (now.getTime() > item.expiry) {
    // If the item is expired, delete the item from storage
    // and return null
    localStorage.removeItem(ttlKey);
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}

// export function cleanToken(key: string): void {
//   const ttlKey = `${key}${TTL}`;
//   localStorage.removeItem(ttlKey);
//   localStorage.removeItem(key);
//   alert('已清理登录凭据，请关闭重新打开系统！');
// }

export function emptyToken(): void {
  localStorage.removeItem(`${ACCESSTOKEN}${TTL}`);
  localStorage.removeItem(ACCESSTOKEN);
  // 同时清理用户信息
  localStorage.removeItem(`${USE_INFO}${TTL}`);
  localStorage.removeItem(USE_INFO);

  alert('已清理登录凭据,同时清理了用户信息，请关闭重新打开系统！');
}

export async function deCode(code: string, state: string, defaultGetSet: any) {
  try {
    // 第一个为自创应用时的读取方法
    const url = `${urlPrefix}/api/rayplatform/user/get-access-token-of-oa?code=${code}&state=${state}`;
    const response = await fetch(url, defaultGetSet);

    if (response.ok) {
      return response.json();
    } else {
      switch (response.status) {
        case 404:
          return { code: 404, msg: '地址错误,请确认请求地址是否正确' };
        case 400:
          return { code: 400, msg: '服务器无法理解客户端发送的请求' };
        case 500:
          return { code: 500, msg: '服务器错误,请联系管理员' };
        case 401:
          //message.error("权限不足,登录失败,请联系管理员");
          break;
        case 403:
          //message.error("权限不足,请联系管理员");
          break;
        default:
          //message.error("程序异常,操作失败");
          break;
      }
      return {
        code: response.status,
        msg: response.statusText,
      };
    }
  } catch (e) {
    console.log(e);
    //message.error("请求异常，GET请求发送失败！");
    return {
      code: 1400,
      msg: `请求异常${e}`,
    };
  }
}

function getUserInfo(model: UseAuthModel): void {
  // 如果本地存储中有数据，就不再向服务器搜索了。
  const current = getWithExpiry(USE_INFO);
  if (current) {
    console.log('current', JSON.parse(current));
    model.signin(JSON.parse(current));
    return;
  }

  const headers = {
    Authorization: `Bearer ${localStorage.getItem(ACCESSTOKEN)}`,
  };
  request(`/api/auth/get-oa-user`, { headers, method: 'GET', data: {} }).then(
    ({ data, code, msg }: any) => {
      if (code === 0) {
        model.signin(data);
        setWithExpiry(USE_INFO, JSON.stringify(data), 30 * 24 * 60 * 60 * 1000);
      } else {
        console.error(msg);
      }
    },
  );
}

export function checkAuthorize(
  setTokening: (a: boolean) => void,
  setAuthOK: (a: boolean) => void,
  setTokenFail: (a: string | undefined) => void,
  model: UseAuthModel,
) {
  const token = localStorage.getItem(ACCESSTOKEN);
  const ttlToken = getWithExpiry(ACCESSTOKEN);
  const authed = ttlToken && token;

  if (authed) {
    getUserInfo(model);
    setAuthOK(true);
    setTokening(false);
  return;
  }
  // 这个是固定值，不同的企业之间可以用同一个值，且会作为state传递到deCode对应的服务器地址
  const fixed = '187f1c7a531a042fb8cd15d5e3ce8b04f';

  if (window.location.search) {
    if (!authed) {
      console.log('document.URL=', document.URL);
      const url = new URL(document.URL);
      const params = url.searchParams;
      const code = params.get('code');
      const state = params.get('state');
      if (code && state && state === fixed && code.length > 2) {
        // 获取 token...
        setTokening(true);
        const defaultGetSet = {
          method: 'GET',
          mode: 'cors',
          cache: 'no-cache',
          credentials: 'same-origin',
          redirect: 'follow',
        };
        // 提交到服务器，获取token
        deCode(code, state, defaultGetSet).then(({ data, code, msg }) => {
          if (code === 0) {
            const { accessToken, tokenType } = data;
            //alert('accessToken=' + accessToken + ",tokenType=" + tokenType);
            setWithExpiry(ACCESSTOKEN, accessToken, 30 * 24 * 60 * 60 * 1000);
            window.location.replace(url.href.replace(url.search, ''));
            // 将code 和status去了，
            setAuthOK(true);
            getUserInfo(model);
          } else {
            //alert('出错啦！msg=' + msg);
            setTokenFail(msg);
          }
          setTokening(false);
        });
      } else {
        setTokening(false);
      }
    }
  } else {
    if (!authed) {
      //let agentId: string, appid: string;
      // http%3A%2F%2Fqywx-ui.billschen.com
      //window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx371e6bb2d19e8c74&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_base&state=${fixed}&agentid=1000004#wechat_redirect`)
      // 平方土地
      let agentId =0;
      let appid ='';
      if(pingfang ){
        agentId = 1000011;
        appid = 'wpZrFfCgAAU2icZy6Z401xJh7ngi27mg';
      }
      if(xinghua){
      // 国地兴华
      agentId =  1000002;
      appid =  'wpZrFfCgAAvKAZKA3IZ3s9zIHNeAk-ag';
      }
      if( hubeismartworker){
        agentId =  1000002;
        appid =  'wpZrFfCgAAyrLJq56q3lBU9lUFEvLWRw';
      }

      if( chongqingguoce){
        agentId =  1000006;
        appid =  'wpZrFfCgAAa_FJ-fUv_V15UznIRpZpUA'
      }
      if(daliangeosmarthub){
        agentId =  1000002;
        appid =  'wpZrFfCgAA2yHdDqAPQTn0qQZouVZAgQ'
      }

      if(baogangecg){
        agentId =  1000003;
        appid =  'wpZrFfCgAAQy43XN3y3B_AbjBTCYw-gw'
      }
      
      // 广州存银
      // const agentId = 1000013;
      // const appid = 'wpZrFfCgAA5ARa62Wh7g1FCEmWkwJNLg';

      // let agentId: number = -1;
      // let appid: string = '没找到appid';
      // agentId = 1000011;
      // appid = 'wpZrFfCgAAU2icZy6Z401xJh7ngi27mg';

      // if (pingfang) {
      //   agentId = 1000011;
      //   appid = 'wpZrFfCgAAU2icZy6Z401xJh7ngi27mg';
      // }

      // if (xinghua) {
        // agentId =  1000002;
        // appid =  'wpZrFfCgAAvKAZKA3IZ3s9zIHNeAk-ag';
      // }

      // ifchongqingguoce ){
      //   agentId =  1000006;
      //   appid =  'wpZrFfCgAAa_FJ-fUv_V15UznIRpZpUA'
      // }
      
      // const headers = { "Content-Type": "application/json" }
      // const requestInit: RequestInit = { mode: 'cors', cache: 'no-cache', credentials: 'same-origin', redirect: 'follow', method: 'get', headers };
      // let response: Promise<Response> = fetch(`${urlPrefix}$/api/qywx-sass-custom-app-tpl-create/get-auth2-url`, requestInit)
      // response.then((rsp: Response) => {
      //     console.log(rsp);
      //     if (rsp.ok) {
      //         rsp.json().then(({ data, code, msg }: DetailResult<string>) => {
      //             if (code === 0) {
      //               //alert(data!);
      //               window.location.replace(data!);
      //             } else {
      //                 setTokening(false);
      //                 setTokenFail(msg);
      //             }
      //         }).catch(reason => {
      //             setTokening(false);
      //             setTokenFail(reason);
      //         })
      //     }
      // }).catch((reason: any) => {
      //     console.error(reason);
      //     setTokening(false);
      //     setTokenFail(`发生错误：${reason}-8845-6512-3302-7412`)
      // }).finally(() => {
      //     //setLoading(false);
      // })

      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
        window.location.href,
      )}&response_type=code&scope=snsapi_privateinfo&state=${fixed}&agentid=${agentId}#wechat_redirect`;
      // alert(url);
      window.location.replace(url);
    } else {
      setAuthOK(true);
      setTokening(false);
    }
  }
}
